﻿using ContactSMS.Commons.QueryParameters;
using ContactSMS.Commons.Responses;
using ContactSMS.Domain;
using ContactSMS.Domain.Entity;
using ContactSMS.WebAPI.Common;
using ContactSMS.WebAPI.Controllers.Request;
using ContactSMS.WebAPI.Controllers.Responses;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;

namespace ContactSMS.WebAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class PhoneRecordController : ControllerBase
    {
        private readonly IPhoneRecordRepository _phoneRecordRepository;
        private readonly IPhoneRepository _phoneRepository;
        private readonly TokenService _tokenService;

        public PhoneRecordController(IPhoneRecordRepository phoneRecordRepository, IPhoneRepository phoneRepository, TokenService tokenService)
        {
            this._phoneRecordRepository = phoneRecordRepository;
            this._phoneRepository = phoneRepository;
            this._tokenService = tokenService;
        }

        [HttpGet]
        public async Task<IActionResult> GetPhoneRecords([FromQuery] PhoneRecordQueryParameters parameters, int page = 1, int pageSize = 10)
        {
            try
            {
                var contacts = await _phoneRecordRepository.GetPhoneRecordsAsync(parameters, page, pageSize);
                var resp = new ServiceResponse<PhoneRecordsSearchResponse>()
                {
                    Data = new PhoneRecordsSearchResponse
                    {
                        list = contacts.PhoneRecords,
                        CurrentPage = page,
                        Pages = (int)contacts.TotalPages
                    }
                };
                return Ok(resp);
            }
            catch (Exception ex)
            {
                ServiceResponse<List<PhoneRecord>> resp = new ServiceResponse<List<PhoneRecord>>();
                resp.Success = false;
                resp.Message = "暂无数据";
                return StatusCode(500, resp);
            }
        }

        [HttpGet]
        [Route("{id:long}")]
        public async Task<IActionResult> GetById([FromRoute] long id)
        {
            var (record, otherRecords) = await _phoneRecordRepository.GetPhoneRecordsByIdAsync(id);
            if (record == null)
            {
                return NotFound("通话记录未找到");
            }
            var resp = new ServiceResponse<PhoneRecordResponse>
            {
                Data = new PhoneRecordResponse
                {
                    Record = record,
                    OtherRecords = otherRecords
                }
            };
            return Ok(resp);
        }

        [HttpPost]
        public async Task<IActionResult> Create([FromBody] AddPhoneRecordRequest addPhoneRecordRequest)
        {
            var userId = _tokenService.GetUserIdFromRequest(Request);
            if (userId == 0)
            {
                return Unauthorized("Invalid token.");
            }
            long ContactId = 0;
            var Phone = await _phoneRepository.GetPhoneByMobileAsync(addPhoneRecordRequest.Mobile);
            if (Phone != null)
            {
                ContactId = Phone.ContactId;
            }
            var DomainModel = new PhoneRecord(addPhoneRecordRequest.Mobile, addPhoneRecordRequest.Status, addPhoneRecordRequest.CallTime, ContactId, userId);
            ;
            await _phoneRecordRepository.AddPhoneRecordAsync(DomainModel);
            ServiceResponse<PhoneRecord> resp = new ServiceResponse<PhoneRecord> { Data = DomainModel };
            return Ok(resp);
        }

        [HttpPost]
        public async Task<IActionResult> Synch([FromBody] SynchPhoneRecordRequest synchPhoneRecordRequest)
        {
            var userId = _tokenService.GetUserIdFromRequest(Request);
            if (userId == 0)
            {
                return Unauthorized("Invalid token.");
            }

            List<PhoneRecord> phoneRecords = new List<PhoneRecord>();

            foreach (var item in synchPhoneRecordRequest.PhoneRecords)
            {
                long ContactId = 0;
                var phone = await _phoneRepository.GetPhoneByMobileAsync(item.Mobile);
                if (phone != null)
                {
                    ContactId = phone.ContactId;
                }
                var DomainModel = new PhoneRecord(item.Mobile, item.Status, item.CallTime, ContactId, userId);
                phoneRecords.Add(DomainModel);
            }
            await _phoneRecordRepository.SynchAsync(phoneRecords);
            ServiceResponse<List<PhoneRecord>> resp = new ServiceResponse<List<PhoneRecord>> { Data = phoneRecords };
            return Ok(resp);
        }

        [HttpDelete]
        [Route("{id:long}")]
        public async Task<IActionResult> DeleteById([FromRoute] long id)
        {
            ServiceResponse<bool> resp = new ServiceResponse<bool>();
            var ex = await _phoneRecordRepository.GetPhoneRecordByIdAsync(id);
            if (ex == null)
            {
                resp.Success = false;
                resp.Message = "删除失败";
                return Ok(resp);
            }
            var result = await _phoneRecordRepository.DeletePhoneRecordByMobileAsync(ex.Mobile);
            if (result)
            {
                resp.Success = true;
                resp.Message = "删除成功";
                return Ok(resp);

            }
            resp.Success = false;
            resp.Message = "删除失败";
            return Ok(resp);
        }

        [HttpDelete]
        [Route("{mobile}")]
        public async Task<IActionResult> DeleteByMobile([FromRoute] string mobile)
        {
            ServiceResponse<bool> resp = new ServiceResponse<bool>();
            var result = await _phoneRecordRepository.DeletePhoneRecordByMobileAsync(mobile);
            if (result)
            {
                resp.Success = true;
                resp.Message = "删除成功";
                return Ok(resp);

            }
            resp.Success = false;
            resp.Message = "删除失败";
            return NotFound(resp);
        }

        [HttpPost]
        public async Task<IActionResult> DeletePhoneRecords([FromBody] List<long> ids)
        {
            ServiceResponse<bool> resp = new ServiceResponse<bool>();
            if (ids == null || ids.Count == 0)
            {
                resp.Success = false;
                resp.Message = "删除失败";
                return BadRequest(resp);
            }
            var deleteds = await _phoneRecordRepository.DeletePhoneRecordByIdsAsync(ids.ToArray());
            if (deleteds)
            {
                resp.Success = true;
                resp.Message = "删除成功";
                resp.Data = deleteds;
                return Ok(resp);
            }
            resp.Success = false;
            resp.Message = "删除失败";
            return BadRequest(resp);
        }
    }
}
